package com.atzxh.java;

import static java.lang.Thread.sleep;

/**
 * @author 小红同学
 * @creat 2021-11-09-10:27
 * @description  解决实现 Runnable 接口类的线程安全问题
 */
class Window4 implements Runnable{

    private int ticket = 100;
//    Object obj = new Object();
    @Override
    public void run() {
        while(true){
            //把sleep 放到synchronized 之前,就不会出现运行时只有一个窗口在卖票
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // synchronized(obj)
            synchronized (this){     //此时this代表唯一的window4对象,不需要再去new一个新对象,
                if(ticket > 0){      //this这种方式只能在Runnable 中用,在继承Thread类中不能用,因为
                                     //Thread中本身已经new了三个window对象.
                    System.out.println(Thread.currentThread().getName()+"卖票,票号为:"+ticket);
                    ticket--;
                }else{
                    break;
                }
            }
        }
    }
}

public class WindowTest3 {
    public static void main(String[] args) {
        Window4 w = new Window4();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();

    }
}

